<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 验证ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: user.php?error=无效的用户ID');
    exit;
}
$id = (int)$_GET['id'];

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$user = null;
$error = '';

// 加载用户数据
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $stmt = $pdo->prepare("SELECT id, username, email, is_admin, status FROM user WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        header('Location: user.php?error=用户不存在');
        exit;
    }
} catch (PDOException $e) {
    $error = "用户加载失败：" . $e->getMessage();
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user) {
    $email = trim($_POST['email'] ?? '');
    $isAdmin = (int)($_POST['is_admin'] ?? 0);
    $status = (int)($_POST['status'] ?? 1);
    $password = trim($_POST['password'] ?? '');
    $confirmPwd = trim($_POST['confirm_password'] ?? '');

    // 禁止修改自己的管理员权限
    if ($id == $_SESSION['user_id'] && $isAdmin != $user['is_admin']) {
        $error = "不能修改当前登录账号的管理员权限";
    } 
    // 禁止禁用自己
    elseif ($id == $_SESSION['user_id'] && $status != 1) {
        $error = "不能禁用当前登录账号";
    }
    // 密码验证（为空则不更新密码）
    elseif (!empty($password)) {
        if (strlen($password) < 6) {
            $error = "密码长度不能少于6个字符";
        } elseif ($password != $confirmPwd) {
            $error = "两次输入的密码不一致";
        }
    }
    // 邮箱验证
    elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "邮箱格式不正确";
    } else {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            
            // 构建更新语句（密码可选更新）
            $updateFields = [
                'email = :email',
                'is_admin = :admin',
                'status = :status'
            ];
            $params = [
                ':email' => $email,
                ':admin' => $isAdmin,
                ':status' => $status,
                ':id' => $id
            ];

            // 如果填写了密码，则更新密码
            if (!empty($password)) {
                $updateFields[] = 'password = :password';
                $params[':password'] = password_hash($password, PASSWORD_DEFAULT);
            }

            $stmt = $pdo->prepare("UPDATE user SET " . implode(', ', $updateFields) . " WHERE id = :id");
            $stmt->execute($params);

            header('Location: user.php?success=用户信息更新成功');
            exit;
        } catch (PDOException $e) {
            $error = "更新失败：" . $e->getMessage();
        }
    }
    // 保留提交数据
    $user['email'] = $email;
    $user['is_admin'] = $isAdmin;
    $user['status'] = $status;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑用户 - IT知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <div class="admin-container">
        <!-- 统一侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item">
                    <a href="index.php" class="nav-link">
                        <i class="fas fa-home"></i>
                        <span>管理首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="article.php" class="nav-link">
                        <i class="fas fa-file-alt"></i>
                        <span>文章管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="category.php" class="nav-link">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="version.php" class="nav-link">
                        <i class="fas fa-sync-alt"></i>
                        <span>版本管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="user.php" class="nav-link active">
                        <i class="fas fa-users"></i>
                        <span>用户管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="logout.php" class="nav-link">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
        </aside>

        <!-- 内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">编辑用户</h1>
                    <a href="user.php" class="btn btn-outline">
                        <i class="fas fa-arrow-left"></i>返回列表
                    </a>
                </div>

                <?php if ($error): ?>
                    <div class="message message-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <?php if ($user): ?>
                    <div class="form-card">
                        <form method="post" action="user_edit.php?id=<?php echo $id; ?>">
                            <div class="form-group">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" 
                                    value="<?php echo htmlspecialchars($user['username']); ?>" 
                                    disabled 
                                    style="background-color: #f8fafc; cursor: not-allowed;">
                                <div class="form-hint">用户名不可修改</div>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="email">
                                    邮箱
                                </label>
                                <input type="email" id="email" name="email" class="form-control" 
                                    placeholder="用于密码找回" 
                                    value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="password">
                                    密码
                                </label>
                                <input type="password" id="password" name="password" class="form-control" 
                                    placeholder="不修改请留空，至少6个字符">
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="confirm_password">
                                    确认密码
                                </label>
                                <input type="password" id="confirm_password" name="confirm_password" class="form-control" 
                                    placeholder="再次输入密码">
                            </div>

                            <div class="inline-fields">
                                <div class="form-group">
                                    <label class="form-label" for="is_admin">
                                        用户角色
                                    </label>
                                    <select id="is_admin" name="is_admin" class="form-control"
                                        <?php echo $id == $_SESSION['user_id'] ? 'disabled' : ''; ?>>
                                        <option value="0" <?php echo $user['is_admin'] == 0 ? 'selected' : ''; ?>>普通用户</option>
                                        <option value="1" <?php echo $user['is_admin'] == 1 ? 'selected' : ''; ?>>管理员</option>
                                    </select>
                                    <?php if ($id == $_SESSION['user_id']): ?>
                                        <div class="form-hint">不能修改当前登录账号的角色</div>
                                    <?php endif; ?>
                                </div>

                                <div class="form-group">
                                    <label class="form-label" for="status">
                                        账号状态
                                    </label>
                                    <select id="status" name="status" class="form-control"
                                        <?php echo $id == $_SESSION['user_id'] ? 'disabled' : ''; ?>>
                                        <option value="1" <?php echo $user['status'] == 1 ? 'selected' : ''; ?>>正常</option>
                                        <option value="0" <?php echo $user['status'] == 0 ? 'selected' : ''; ?>>禁用</option>
                                    </select>
                                    <?php if ($id == $_SESSION['user_id']): ?>
                                        <div class="form-hint">不能禁用当前登录账号</div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i>更新用户
                                </button>
                                <a href="user.php" class="btn btn-outline">
                                    <i class="fas fa-times"></i>取消
                                </a>
                            </div>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
</body>
</html>